# database.py
from datetime import timedelta

from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import os


## 配置数据库
HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = 'flask-test'
USERNAME = 'root'
PASSWORD = '123456'

## 配置应用
config = {
    ## 一、mysql配置
    ## 连接配置
    "SQLALCHEMY_DATABASE_URI":f'mysql+mysqldb://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}',
    ## 未知
    "SQLALCHEMY_BINDS":{},
    ## 修改跟踪
    "SQLALCHEMY_TRACK_MODIFICATIONS":False,
    ## 输入底层sql
    "SQLALCHEMY_ECHO":True,
    ## 自动提交
    "SQLALCHEMY_COMMIT_ON_TEARDOWN":True,

    ## 二、session配置
    'SECRET_KEY': "flask123456",
    'PERMANENT_SESSION_LIFETIME': timedelta(days=15)
}

## 定义配置项
def defineSettings(app):
    ## 创建sqlalchemy关联数据库
    db = SQLAlchemy()
    # 配置数据库
    app.config = {**app.config, **config}
    # 绑定app和数据库
    db.init_app (app)
    migrate = Migrate(app,db)
    return db

## 配置项执行任务
def defineSettingsExecute(db):
    # 执行映射模型
    defineMdels(db)


## 自定义模型
def defineMdels(db):
    class User(db.Model):
        id = db.Column(db.Integer,primary_key=True)
        username = db.Column(db.String(50))
        addresses = db.relationship('Address',backref='user')

        # def __init__(self,username):
        #     self.username = username

    class Address(db.Model):
        id = db.Column(db.Integer,primary_key=True)
        email_address = db.Column(db.String(50))
        user_id = db.Column(db.Integer,db.ForeignKey('user.id'))

        # def __init__(self,email_address):
        #     self.email_address = email_address

